/**
 * Get the list of agents and make the select box for them 
 */
function initInfo(living) {
    $.ajax({
        url: "functions/ajax/getAgentList.php",
        context: self,
        type: "post",
        success: function(data, textStatus, jqXHR) {
            var agentArray = jQuery.parseJSON(data);

            var agentSelect = $("select#agentSelect");

            agentSelect.empty();

            // first remove the current markers
            for (var i=0; i<agentArray.length; i++) {
                if (agentArray[i].alive == living) {
                    agentSelect.append("<option>"+agentArray[i].name+"</option>");
                }
            }

            agentSelect.selectmenu('refresh');

            agentSelect.change(function() {
                selectAgent(agentSelect.select("option:selected").val());
            }); 
        }
    });
}

function selectAgent(agentId) {
    $.ajax({
        url: "functions/ajax/getAgentDetails.php",
        context: self,
        type: "post",
        data: {name: agentId},
        success: function(data, textStatus, jqXHR) {
            var agentDetails = jQuery.parseJSON(data);

            $("h2#name").html(agentDetails.name);

            // build a string of likes and put it in the DOM
            var likesStr = "";
            for (var i=0; i < agentDetails.likes.length; i++) {
                if (i != 0) {
                    likesStr += ", ";
                }
                likesStr += agentDetails.likes[i];
            }
            $("span#likes").html(likesStr);
            
            // build a string of dislikes and put it in the DOM
            var dislikesStr = "";
            for (var i=0; i < agentDetails.dislikes.length; i++) {
                if (i != 0) {
                    dislikesStr += ", ";
                }
                dislikesStr += agentDetails.dislikes[i];
            }
            $("span#dislikes").html(dislikesStr);
            
            // build a string of friends and put it in the DOM
            var friendsStr = "";
            for (var i=0; i < agentDetails.friends.length; i++) {
                if (i != 0) {
                    friendsStr += ", ";
                }
                friendsStr += agentDetails.friends[i];
            }
            $("span#friends").html(friendsStr);
        }
    });
}

var infoInitialized;
if (!infoInitialized) {
    infoInitialized = true;
    $('#info').live('pageinit',function(event){
        initInfo(true);
    
        $('a#toggleLiving').click(function() {
            var span = $("span#toggleText");
            if (span.text() == "Living") {
                initInfo(false);
                span.text("Dead");
            } else {
                initInfo(true);
                span.text("Living");
            }
        });
    });

}

